package com.wlyuan.index.domain.index.valueobj;

import com.wlyuan.index.domain.source.valueobj.Highlight;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author yuanjie
 */
@Data
@Slf4j
@Deprecated
@EqualsAndHashCode(exclude = {"quotations"})
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public abstract class Relation {
    protected Optional<Quotation> quotation() {
        if (CollectionUtils.isEmpty(quotations)) {
            return Optional.empty();
        }
        return quotations.stream().max(Comparator.comparingInt(Quotation::getPriority));
    }

    synchronized public void addQuotation(Quotation quotation) {
        if (null == this.quotations) {
            this.quotations = new ArrayList<>();
        }
        var quotationMap = this.quotations.stream().collect(Collectors.toMap(Quotation::getQuotationId, a -> a));
        quotationMap.put(quotation.getQuotationId(), quotation);
        this.quotations = new ArrayList<>(quotationMap.values());
    }

    protected void closeQuote() {
        this.setQuotationStatus(QuotationStatus.CLOSED.getValue());
    }

    protected boolean endQuote() {
        return BooleanUtils.isTrue(this.endQuote);
    }

    public void addHighlight(Highlight highlight, Integer marked) {
        if (!Highlight.marked(marked)) {
            return;
        }
        synchronized (this) {
            if (null == this.highlights) {
                this.highlights = new ArrayList<>();
            }
        }
        this.highlights.add(highlight.getValue());
    }


    @Field(type = FieldType.Integer)
    private Integer character;
    @Field(type = FieldType.Integer)
    private Integer status;
    @Field(type = FieldType.Long)
    private Long quotationId;
    @Field(type = FieldType.Keyword)
    private String quotationNo;
    @Field(type = FieldType.Integer)
    private Integer quotationStatus;
    @Field(type = FieldType.Boolean)
    private Boolean callQuote;
    @Field(type = FieldType.Boolean)
    private Boolean endQuote;
    @Field(type = FieldType.Nested, index = false)
    private List<Quotation> quotations;
    @Field(type = FieldType.Nested)
    private WaybillSign sign;
    @Field(type = FieldType.Nested)
    private WaybillReceipt receipt;
    @Field(type = FieldType.Integer)
    private List<Integer> highlights;
    @Field(type = FieldType.Long)
    private Long tenantId;
}